package com.example.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.common.Result;
import com.example.demo.entity.BdEntry;
import com.example.demo.entity.response.EntryResponse;
import com.example.demo.mapper.EntryMapper;
import com.example.demo.service.EntryService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/entry")
public class EntryController extends BaseController{

    @Resource
    EntryMapper entryMapper;

    @Autowired
    EntryService entryService;

    @PostMapping
    public Result<?> save(@RequestBody BdEntry bdEntry) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        String jsonString = objectMapper.writeValueAsString(bdEntry);
        Map<String, Object> jsonObject = objectMapper.readValue(jsonString, Map.class);

        // 提取Map对象的键作为KeySet
        Set<String> keySet = jsonObject.keySet();

        // 输出KeySet中的元素
        for (String key : keySet) {
            String value = (String) jsonObject.get(key);
            if ("不合格".equals(value)){
                bdEntry.setUnqualifiedNum(true);
                break;
            }
        }
        entryMapper.insert(bdEntry);
        return Result.success();
    }

    @PutMapping("/materials")
    public Result<?> updateMaterials(@RequestBody EntryResponse EntryResponse) {

        LambdaQueryWrapper<BdEntry> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BdEntry::getActivityId, EntryResponse.getActivityId());
        BdEntry bdEntry = entryMapper.selectOne(wrapper);

        if(bdEntry == null){
            BdEntry newBdEntry =new BdEntry();
            newBdEntry.setSubmittedMaterials(EntryResponse.getSubmittedMaterials());
            newBdEntry.setActivityId(EntryResponse.getActivityId());
            entryMapper.insert(newBdEntry);
        }else{
            entryMapper.updateById(bdEntry);
        }
//        if (Stringuentry.getSubmittedMaterials()){
//            String material = "";
//            for(String item : entryResponse.getSubmittedMaterials()){
//                material += item + ",";
//            }
//            material = material.substring(0, material.length()-1);
//            entry.setSubmittedMaterials(material);
//        }else{
//            entry.setSubmittedMaterials("");
//        }


        return Result.success();
    }

    @PutMapping()
    public Result<?> update(@RequestBody BdEntry bdEntry) throws JsonProcessingException {

//        LambdaQueryWrapper<Entry> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(Entry::getActivityId, entryResponse.getActivityId());
//        Entry entry = entryMapper.selectOne(wrapper);
//        BeanUtils.copyProperties(entryResponse,entry);
//
//        if (entryResponse.getUnloadingPoint()!=null&&entryResponse.getUnloadingPoint().length>0){
//            String point = "";
//            for(String item : entryResponse.getUnloadingPoint()){
//                point += item + ",";
//            }
//            point = point.substring(0, point.length()-1);
//            entry.setUnloadingPoint(point);
//        }else{
//            entry.setUnloadingPoint("");
//        }
//        if (entryResponse.getUnloadingPoint()!=null&&entryResponse.getUnloadingPoint().length>0){
//            String elevators = "";
//            for(String item : entryResponse.getUnloadingPoint()){
//                elevators += item + ",";
//            }
//            elevators = elevators.substring(0, elevators.length()-1);
//            entry.setElevatorsUsed(elevators);
//
//        }else{
//            entry.setElevatorsUsed("");
//        }
//        if (entryResponse.getFreightMovementLine()!=null&&entryResponse.getFreightMovementLine().length>0){
//            String line = "";
//            for(String item : entryResponse.getFreightMovementLine()){
//                line += item + ",";
//            }
//            line = line.substring(0, line.length()-1);
//            entry.setFreightMovementLine(line);
//        }else{
//            entry.setFreightMovementLine("");
//        }
        ObjectMapper objectMapper = new ObjectMapper();

        String jsonString = objectMapper.writeValueAsString(bdEntry);
        Map<String, Object> jsonObject = objectMapper.readValue(jsonString, Map.class);

        // 提取Map对象的键作为KeySet
        Set<String> keySet = jsonObject.keySet();

        // 输出KeySet中的元素
        for (String key : keySet) {
            String value = (String) jsonObject.get(key);
            if ("不合格".equals(value)){
                bdEntry.setUnqualifiedNum(true);
                break;
            }
        }
        LambdaQueryWrapper<BdEntry> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BdEntry::getActivityId, bdEntry.getActivityId());
        BdEntry selectOne = entryMapper.selectOne(wrapper);
        if(selectOne == null){
            entryMapper.insert(bdEntry);
        }else{
            bdEntry.setId(selectOne.getId());
            entryMapper.updateById(bdEntry);
        }
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        entryMapper.deleteById(id);
        return Result.success();
    }

//    @PostMapping("/deleteBatch")
//    public Result<?> deleteBatch(@RequestBody List<Integer> ids) {
//        entryMapper.deleteBatchIds(ids);
//        return Result.success();
//    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Integer id) {
        return Result.success(entryMapper.selectByActiveId(id));
    }

    /**
     * 导出案例
     *
     * @param id
     * @return RestResponse
     */
    @ApiOperation(value = "导出进场单", notes = "导出进场单")
    @GetMapping(value = "/export/{id}")
    public void export(@PathVariable Integer id, HttpServletResponse response) throws Exception {
        BdEntry bdEntry =entryMapper.selectByActiveId(id);
        entryService.exportToPdf(bdEntry, response);
    }

//    @GetMapping
//    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
//                              @RequestParam(defaultValue = "10") Integer pageSize
//                              ) {
//        LambdaQueryWrapper<Entry> wrapper = Wrappers.<Entry>lambdaQuery();
//        Page<Entry> entryPage = entryMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
//        return Result.success(entryPage);
//    }
}
